from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from school.serializers import SchoolListSerializer

User = get_user_model()



class UserCreateSerializer(serializers.ModelSerializer):
    """用户注册序列"""
    mobile = serializers.CharField(required=True, max_length=11, min_length=11, label="手机号码",
                                   error_messages={
                                       "blank": "请输入手机号码",
                                       "required": "请输入手机号码",
                                       "max_length": "手机号码格式错误",
                                       "min_length": "手机号码格式错误"
                                   },
                                   help_text="手机号码",
                                   validators=[UniqueValidator(queryset=User.objects.all(),
                                                               message="电话号码不允许重复")])
    username = serializers.CharField(label="用户名", help_text="用户名", required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已经存在")])
    password = serializers.CharField(
        style={'input_type': 'password'}, help_text="密码", label="密码", write_only=True,
    )

    def create(self, validated_data):
        user = super(UserCreateSerializer, self).create(validated_data=validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user

    class Meta:
        model = User
        fields = ('id', 'username', 'gender', 'mobile','password','is_active','school')


class UserListSerializer(serializers.ModelSerializer):
    """
    用户详情序列化类
    """
    gender = serializers.SerializerMethodField()
    school = SchoolListSerializer()
    class Meta:
        model = User
        fields = ("id", "username", "gender", "email", "mobile",'school')

    def get_gender(self, obj):
        return obj.get_gender_display()


class UserJWTSerializer(serializers.ModelSerializer):
    """
    用户JWT返回序列化类
    """
    school = SchoolListSerializer()
    class Meta:
        model = User
        fields = ("id", "username", "mobile","is_superuser","school")


